﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;

using ESOL.Common.Entity;
using ESOL.WinUI.Proj;
using ESOL.Business.Prod;
using ESOL.Business.Mst;
using ESOL.Business.Sales;
using ESOL.Common;
using ESOL.Business.Chk;
using ESOL.WinUI.Manufacture;

namespace ESOL.WinUI.Qc
{
    public partial class frmMaintainIPQC : BaseForm.frmBaseDialogyMaintainForm
    {
        #region Variable
        public ActionType ThisActionType { set; get; }
        private ProdPlanOrderItemEntity mSelectedPlanOrderItem;
        private List<QcIpqcOrderItemEntity> listDel = new List<QcIpqcOrderItemEntity>();
        private QcIpqcOrderEntity mSelectedIpqcOrder;
        private QcSamplingParametersEntity mSelectedSamplingParameter;
        #endregion

        #region Constructor
        public frmMaintainIPQC()
        {
            InitializeComponent();
        }
        public frmMaintainIPQC(QcIpqcOrderEntity entity)
        {
            InitializeComponent();
            mSelectedIpqcOrder = entity;
        }
        #endregion

        #region Functions
        private void Init()
        {
            if (ThisActionType == ActionType.View)
            {
                btnSave.Enabled = false;
            }
            else if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                btnSave.Enabled = true;
            }
        }
        private void BindCombobox()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("name");
            dt.Columns.Add("value", typeof(int));
            dt.Rows.Add("全检", 0);
            dt.Rows.Add("抽检", 1);
            cmbCheckType.DataSource = dt;
            cmbCheckType.DisplayMember = "name";
            cmbCheckType.ValueMember = "value";

            string sCondition = " and STATUS='STATUS03' ";
            DataTable dt1 = QcSamplingParametersBs.GetDtAllByCondition(sCondition, "", "");
            cmbSamplingParameters.DataSource = dt1;
            cmbSamplingParameters.DisplayMember = "NAME";
            cmbSamplingParameters.ValueMember = "ID";
        }
        private void BindComboboxStation()
        {
            if (mSelectedPlanOrderItem == null)
                return;
            DataTable dt = ProdProductTechnicBs.GetDtStation(mSelectedPlanOrderItem.PlanOrderItemId, "STT02");
            if (dt.Rows.Count == 0)
            {
                MessageBox.Show("该工令单不存在质检工序！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            cmbStation.DataSource = dt;
            cmbStation.DisplayMember = "TECHNIC_NAME";
            cmbStation.ValueMember = "PRODUCT_TECHNIC_ID";
        }
        private void SetField()
        {
            if (ThisActionType == ActionType.New)
            {
                if (mSelectedPlanOrderItem == null)
                    return;
                MstProductEntity mProduct = MstProductBs.GetMstProductTypeByID(mSelectedPlanOrderItem.ProductId);
                if (mProduct == null)
                    return;
                ProdPlanOrderEntity mPlanOrder = ProdPlanOrderBs.GetProdPlanOrderByID(mSelectedPlanOrderItem.PlanOrderId);
                if (mPlanOrder == null)
                    return;
                SalesProdPlanApplicationItemEntity mApplicationItem = SalesProdPlanApplicationItemBs.GetProdPlanApplicationItemByID(mPlanOrder.ApplicationItemId);
                if (mApplicationItem == null)
                    return;
                txtProductName.Text = mProduct.ProductName;
                txtProductCode.Text = mProduct.ProductCode;
                txtProductDescription.Text = mProduct.Description;
                txtContractModel.Text = mApplicationItem.ProductSpecOut;
                txtProductMaterial.Text = mProduct.Material;
                txtPlanQty.Text = mSelectedPlanOrderItem.Qty.ToString();
                if (cmbCheckType.SelectedValue.ToString().Equals("0"))
                {
                    if (mSelectedPlanOrderItem != null)
                    {
                        txtCheckQty.Text = mSelectedPlanOrderItem.Qty.ToString();
                    }
                }
                else if (cmbCheckType.SelectedValue.ToString().Equals("1"))
                {
                    string sCondition = " and RANGE_MIN_QTY<=" + mSelectedPlanOrderItem.Qty;
                    sCondition += " and RANGE_MAX_QTY>=" + mSelectedPlanOrderItem.Qty;
                    DataTable dt = QcSamplingParametersBs.GetDtAllByCondition(sCondition, "", "");
                    if (dt.Rows.Count == 1)
                    {
                        mSelectedSamplingParameter = new QcSamplingParametersEntity(dt.Rows[0]);
                        txtCheckQty.Text = mSelectedSamplingParameter.CheckQty.ToString();
                    }
                }
            }
            else if (ThisActionType == ActionType.Modify || ThisActionType == ActionType.View)
            {
                if (mSelectedIpqcOrder == null)
                    return;
                mSelectedPlanOrderItem = ProdPlanOrderItemBs.GetProdPlanOrderItemByID(mSelectedIpqcOrder.ProdPlanOrderItemId);
                if (mSelectedPlanOrderItem == null)
                    return;
                MstProductEntity mProduct = MstProductBs.GetMstProductTypeByID(mSelectedPlanOrderItem.ProductId);
                if (mProduct == null)
                    return;
                ProdPlanOrderEntity mPlanOrder = ProdPlanOrderBs.GetProdPlanOrderByID(mSelectedPlanOrderItem.PlanOrderId);
                if (mPlanOrder == null)
                    return;
                SalesProdPlanApplicationItemEntity mApplicationItem = SalesProdPlanApplicationItemBs.GetProdPlanApplicationItemByID(mPlanOrder.ApplicationItemId);
                if (mApplicationItem == null)
                    return;
                BindComboboxStation();
                txtQcOrder.Text = mSelectedIpqcOrder.OrderCode;
                txtWorkingOrder.Text = mSelectedPlanOrderItem.OrderItemCode;
                txtProductName.Text = mProduct.ProductName;
                txtProductCode.Text = mProduct.ProductCode;
                txtProductDescription.Text = mProduct.Description;
                txtContractModel.Text = mApplicationItem.ProductSpecOut;
                txtProductMaterial.Text = mProduct.Material;
                txtPlanQty.Text = mSelectedPlanOrderItem.Qty.ToString();
                txtCheckQty.Text = mSelectedIpqcOrder.CheckQty.ToString();
                txtNgQty.Text = mSelectedIpqcOrder.NgQty.ToString();
                txtCustomDefine1.Text = mSelectedIpqcOrder.CustomDefine1;
                cmbSamplingParameters.SetSelectedValue(mSelectedIpqcOrder.CheckType);
                cmbStation.SetSelectedValue(mSelectedIpqcOrder.ProductTechnicId);
                txtRemark.Text = mSelectedIpqcOrder.Remark;

                UICommon.UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, mSelectedIpqcOrder.CreateBy);
                UICommon.UICommonFunctions.SetTextBoxDate(txtCreateDate, mSelectedIpqcOrder.CreateDate, "yyyy-MM-dd");
                UICommon.UICommonFunctions.SetTextBoxPersonName(txtLastModifiedBy, mSelectedIpqcOrder.LastModifiedBy);
                UICommon.UICommonFunctions.SetTextBoxDate(txtLastModifiedDate, mSelectedIpqcOrder.LastModifiedDate, "yyyy-MM-dd");
            }
        }
        private void BindGrid()
        {
            if (ThisActionType == ActionType.New)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("ORDER_ITEM_ID");
                dt.Columns.Add("ORDER_ID");
                dt.Columns.Add("QTY", typeof(decimal));
                dt.Columns.Add("NG_DESCRIPTION");
                dt.Columns.Add("REMARK");
                dt.Columns.Add("APPROVE_RESULT", typeof(int));
                gvMain.DataSource = dt;
            }
            else if (ThisActionType == ActionType.Modify || ThisActionType == ActionType.View)
            {
                string sCondition = @" and qioi.ORDER_ID='" + mSelectedIpqcOrder.OrderId + "' ";
                DataTable dt = QcIpqcOrderItemBs.GetDtAllByCondition(sCondition);
                gvMain.DataSource = dt;
            }
        }

        private bool CheckData()
        {
            if (mSelectedPlanOrderItem == null)
            {
                MessageBox.Show("工令单不可为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtCustomDefine1.Text))
            {
                MessageBox.Show("定义单号不可为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(cmbCheckType.SelectedValue.ToString()))
            {
                MessageBox.Show("检验类型不可为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(cmbStation.SelectedValue.ToString()))
            {
                MessageBox.Show("质检工序不可为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtCheckQty.Text))
            {
                MessageBox.Show("质检数量不可为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    if (string.IsNullOrEmpty(dr["QTY"].ToString()))
                    {
                        MessageBox.Show("不良明细不可为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
            }
            if (Convert.ToDecimal(txtPlanQty.Text) < Convert.ToDecimal(txtNgQty.Text))
            {
                MessageBox.Show("不良数量超出计划数量！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return true;
        }
        private void SetEntity()
        {
            if (ThisActionType == ActionType.New)
            {
                DataTable dtNg = gvMain.DataSource as DataTable;
                mSelectedIpqcOrder = new QcIpqcOrderEntity();
                mSelectedIpqcOrder.OrderId = Guid.NewGuid().ToString();
                mSelectedIpqcOrder.ProdPlanOrderItemId = mSelectedPlanOrderItem.PlanOrderItemId;
                mSelectedIpqcOrder.Status = "STATUS01";
                if (cmbStation.SelectedValue != null && string.IsNullOrEmpty(cmbStation.SelectedValue.ToString()) == false)
                {
                    mSelectedIpqcOrder.ProductTechnicId = cmbStation.SelectedValue.ToString();
                }
                if (cmbCheckType.SelectedValue != null && string.IsNullOrEmpty(cmbCheckType.SelectedValue.ToString()) == false)
                {
                    mSelectedIpqcOrder.CheckType = Convert.ToInt32(cmbCheckType.SelectedValue.ToString());
                }
                if (cmbSamplingParameters.Enabled == true &&
                    cmbSamplingParameters.SelectedValue != null && string.IsNullOrEmpty(cmbSamplingParameters.SelectedValue.ToString()) == false)
                {
                    mSelectedIpqcOrder.SampingParametersId = cmbSamplingParameters.SelectedValue.ToString();
                }
                mSelectedIpqcOrder.CheckQty = Convert.ToDecimal(txtCheckQty.Text);
                mSelectedIpqcOrder.NgQty = Convert.ToDecimal(txtNgQty.Text);
                if (dtNg.Rows.Count == 0)
                    mSelectedIpqcOrder.ResultTag = 0;
                else mSelectedIpqcOrder.ResultTag = 1;
                mSelectedIpqcOrder.CreateBy = Common.CommonParameter.CurrentUser.PersonId;
                mSelectedIpqcOrder.CreateDate = DateTime.Now;
                mSelectedIpqcOrder.LastModifiedBy = Common.CommonParameter.CurrentUser.PersonId;
                mSelectedIpqcOrder.LastModifiedDate = DateTime.Now;
                mSelectedIpqcOrder.Remark = txtRemark.Text;
                mSelectedIpqcOrder.CustomDefine1 = txtCustomDefine1.Text;
            }
            else if (ThisActionType == ActionType.Modify)
            {
                DataTable dtNg = gvMain.DataSource as DataTable;
                if (cmbCheckType.SelectedValue != null && string.IsNullOrEmpty(cmbCheckType.SelectedValue.ToString()) == false)
                {
                    mSelectedIpqcOrder.CheckType = Convert.ToInt32(cmbCheckType.SelectedValue.ToString());
                }
                if (cmbSamplingParameters.Enabled == true &&
                    cmbSamplingParameters.SelectedValue != null && string.IsNullOrEmpty(cmbSamplingParameters.SelectedValue.ToString()) == false)
                {
                    mSelectedIpqcOrder.SampingParametersId = cmbSamplingParameters.SelectedValue.ToString();
                }
                mSelectedIpqcOrder.CheckQty = Convert.ToDecimal(txtCheckQty.Text);
                mSelectedIpqcOrder.NgQty = Convert.ToDecimal(txtNgQty.Text);
                if (dtNg.Rows.Count == 0)
                    mSelectedIpqcOrder.ResultTag = 0;
                else mSelectedIpqcOrder.ResultTag = 1;
                mSelectedIpqcOrder.LastModifiedBy = Common.CommonParameter.CurrentUser.PersonId;
                mSelectedIpqcOrder.LastModifiedDate = DateTime.Now;
                mSelectedIpqcOrder.Remark = txtRemark.Text;
                mSelectedIpqcOrder.CustomDefine1 = txtCustomDefine1.Text;
            }
        }
        private bool Save()
        {
            DataTable dtNg = gvMain.DataSource as DataTable;
            if (ThisActionType == ActionType.New)
            {
                if (QcIpqcOrderBs.Save(true, mSelectedIpqcOrder, dtNg, listDel) == false)
                {
                    MessageBox.Show("保存失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
            }
            else if (ThisActionType == ActionType.Modify)
            {
                if (QcIpqcOrderBs.Save(false, mSelectedIpqcOrder, dtNg, listDel) == false)
                {
                    MessageBox.Show("保存失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
            }
            return true;
        }
        #endregion

        #region Events
        private void frmMaintainIPQC_Load(object sender, EventArgs e)
        {
            Init();
            BindCombobox();
            SetField();
            BindGrid();
        }

        private void txtWorkingOrder_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainProdPlanOrderItemQuery frm = new frmMaintainProdPlanOrderItemQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProdPlanOrderItem != null)
            {
                txtWorkingOrder.Text = frm.SelectedProdPlanOrderItem.OrderItemCode;
                mSelectedPlanOrderItem = frm.SelectedProdPlanOrderItem;
                BindComboboxStation();
                SetField();
            }
            else
            {
                txtWorkingOrder.Text = "";
                mSelectedPlanOrderItem = null;
            }
        }

        private void txtWorkingOrder_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter)
                return;
            if (string.IsNullOrEmpty(txtWorkingOrder.Text))
                return;
            mSelectedPlanOrderItem = ProdPlanOrderItemBs.GetProdPlanOrderItemByCode(txtWorkingOrder.Text);
            if (mSelectedPlanOrderItem == null)
            {
                MessageBox.Show("工令单号错误！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            BindComboboxStation();
            SetField();
        }

        private void tsNgNew_Click(object sender, EventArgs e)
        {
            DataTable dtNg = gvMain.DataSource as DataTable;
            DataRow dr = dtNg.NewRow();
            dr["ORDER_ITEM_ID"] = Guid.NewGuid().ToString();
            dtNg.Rows.Add(dr);
        }

        private void tsNgDel_Click(object sender, EventArgs e)
        {
            DataRow dr = gridView1.GetFocusedDataRow();
            if (dr == null)
                return;
            DataTable dtNg = gvMain.DataSource as DataTable;
            if (ThisActionType == ActionType.Modify)
            {
                QcIpqcOrderItemEntity m = new QcIpqcOrderItemEntity(dr);
                listDel.Add(m);
            }
            dtNg.Rows.Remove(dr);
        }

        protected override void Click_Save()
        {
            if (CheckData() == false)
                return;
            SetEntity();
            if (Save())
            {
                MessageBox.Show("保存成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.DialogResult = DialogResult.OK;
                return;
            }
        }
        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(e.Value.ToString()))
                return;
            if (e.Column.FieldName.Equals("QTY") == false)
                return;
            DataTable dt = gvMain.DataSource as DataTable;
            decimal dNgTotalQty = 0;
            foreach (DataRow dr in dt.Rows)
            {
                if (string.IsNullOrEmpty(dr["QTY"].ToString()) == false)
                {
                    dNgTotalQty += Convert.ToDecimal(dr["QTY"].ToString());
                }
            }
            txtNgQty.Text = dNgTotalQty.ToString();
        }
        #endregion
    }
}